package com.example.covid19.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.covid19.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * <p>
 *
 * @author data-baker
 */
@RestController
@RequestMapping("/CN")
@Slf4j
public class AsrRestApiDemo {

    private static final String clientId = "2dc4bcbcb2644484ae6ca8a5c126ff21";
    private static final String clientSecret = "19c8ded211ed4" +
            "3c9bc302d05adea081d";

    /**
     * 获取token的地址信息
     */
    public static String tokenUrl = "https://openapi.data-baker.com/oauth/2.0/token?grant_type=client_credentials&client_secret=%s&client_id=%s";
    /**
     * 一句话识别API地址
     */
    public static String asrUrl = "https://openapi.data-baker.com/asr/api";
    /**
     * 音频文件
     */
    public static String audioPath = "D:\\test.wav";
    /**
     * 文件大小限制
     *
     * @param args
     */
    public static Integer MAX_FILE_SIZE = 10 * 1024 * 1024;
    @RequestMapping("/CNS")
    public  Result Asr(@RequestPart("file") MultipartFile multipartFile) {
        String str2;
        str2 = upLoad(multipartFile);
        String accessToken = getAccessToken();
        if (StringUtils.isNotEmpty(accessToken)) {
            File audioFile = new File(str2);
            //一句话在线识别支持的音频长度在60S内，开发者需注意音频流的大小
            if (audioFile.exists() && audioFile.length() < MAX_FILE_SIZE) {
                //支持pcm和wav格式:如果是wav格式，audioFormat设置为"wav";如果是pcm格式，audioFormat设置为"pcm"
                return Result.success(doSpeechRecognition(accessToken, audioFile, "pcm", 16000));
            }
        }
        return Result.fail(401,"错误",null);
    }
    @RequestMapping("/upload")
    public static String upLoad(@RequestPart("file") MultipartFile multipartFile){
        log.info("文件上传开始");
        log.info("文件{}",multipartFile.getOriginalFilename());
        String str;
        if (!multipartFile.isEmpty()){
            try {
                //上传的文件需要保存的路径和文件名称，路径需要存在，否则报错
                multipartFile.transferTo(new File("D:/"+multipartFile.getOriginalFilename()));
                str="D:/"+multipartFile.getOriginalFilename();

            } catch (IllegalStateException | IOException e){
                e.printStackTrace();
                return "上传失败";
            }
        } else {
            return "请上传文件";
        }
        return str;
    }

    public  Result doSpeechRecognition(String accessToken, File audioFile, String audioFormat, Integer sampleRate) {
        try {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/octet-stream");
            FileInputStream in = new FileInputStream(audioFile);
            byte[] fileByte = new byte[(int) audioFile.length()];
            int realLen = in.read(fileByte);
            //确保音频文件内容全部被读取
            if (realLen == (int) audioFile.length()) {
                RequestBody body = RequestBody.create(mediaType, fileByte);
                //构造request
                Request request = new Request.Builder()
                        .url(asrUrl)
                        .addHeader("access_token", accessToken)
                        .addHeader("audio_format", audioFormat)
                        .addHeader("sample_rate", String.valueOf(sampleRate))
                        .addHeader("domain", "common")
                        .method("POST", body)
                        .build();
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    JSONObject jsonObject = JSON.parseObject(response.body().string());
                    System.out.println("成功" + (jsonObject == null ? "" : jsonObject.getString("text")));
//                    return Result.success(200,"成功",(jsonObject == null ? "" : jsonObject.getString("text")));
                        return Result.success((jsonObject == null ? "" : jsonObject.getString("text")));
                } else {
                    System.out.println("失败" + response.body().string());
                    return Result.fail(404,"未识别语音",response.body().string());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success(001,"返回",null);
    }


    public static String getAccessToken() {
        String accessToken = "";
        OkHttpClient client = new OkHttpClient();
        //request 默认是get请求
        String url = String.format(tokenUrl, clientSecret, clientId);
        Request request = new Request.Builder().url(url).build();
        JSONObject jsonObject;
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                //解析
                String resultJson = response.body().string();
                jsonObject = JSON.parseObject(resultJson);
                accessToken = jsonObject.getString("access_token");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
}
